/*
 * Copyright (c) 2012 Banaanvraag
 * MIT Licence.
 */
package banaanvraag.tools.conversion;

import java.awt.image.BufferedImage;
import java.util.HashMap;
import banaanvraag.tools.btm.BTM;
import banaanvraag.tools.btm.Gridbit;
import java.util.Map;

/**
 * Tools for converting between BTM and BufferedImage. Useful for simple graphics and im- and export of image files.
 * @author Luc
 */
public class BTMConversion {

    /**
     * Take BTM and create a BufferedImage from it. 1 gridbit equals to one pixel.
     * @param btm The BTM with all data.
     * @param colourmap A Map for linking types to colours. If you're using very low values, these will result in almost indistinguishable black.
     * Using a colourmap you can map these values to brighter and better colours.
     * @return A complete BufferedImage.
     */
    public static BufferedImage btmToBufferedImage(BTM btm, Map<Integer, Integer> colourmap) {
        BufferedImage ret = new BufferedImage(btm.getSizeX(), btm.getSizeY(),
                BufferedImage.TYPE_INT_RGB);
        
        int j, i = 0;
        while(i < btm.getSizeX()) {
            j = 0;
            while(j < btm.getSizeY()) {
                int rgb = colourmap.containsKey(btm.get(i, j).getType()) ? colourmap.get(btm.get(i, j).getType()) : btm.get(i, j).getType();
                ret.setRGB(i, j, rgb);
                j++;
            }
            i++;
        }
        
        return ret;
    }
    
    /**
     * Takes a BufferedImage and creates a BTM of it. 1 pixel equals 1 gridbit.
     * @param img The BufferedImage
     * @param colourmap A map for linking colours to types. Useful when the colours in the image are only presentational and the program expects different values.
     * @return A complete BTM.
     */
    public static BTM bufferedImageToBTM(BufferedImage img, Map<Integer, Integer> colourmap) {
        BTM ret = new BTM(img.getWidth(), img.getHeight());
        
        int j, i = 0;
        while(i < img.getWidth()) {
            j = 0;
            while(j < img.getHeight()) {
                int rgb = colourmap.containsKey(img.getRGB(i, j)) ? colourmap.get(img.getRGB(i, j)) : img.getRGB(i, j);
                ret.put(i, j, new Gridbit(rgb, 0));
                j++;
            }
            i++;
        }
        
        return ret;
    }
}
